package com.live.shop.home.setting;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.home.setting.adapter.PageFragment;
import com.live.shop.model.AliyunVoiceModel;
import com.live.shop.model.UserModel;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.TtsMessageEvent;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AliyunActivity extends BaseActivity {
    ImageButton aliyun_back;
    ImageView aliyun_question;
    TextView aliyun_save;
    EditText aliyun_appkey;
    EditText aliyun_AccessKeyID;
    EditText aliyun_AccessKeySecret;
    EditText aliyun_volume;
    EditText aliyun_speed;
    TextView aliyun_voice_select;
    TabLayout aliyun_tablayout;
    ViewPager2 aliyun_viewpager2;

    UserDatabase userDb ;
    String font_name;
    String[] tar = new String[]{"通用","直播","客服","多语种","方言","英文","儿童"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aliyun);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        //首先要在你要接受EventBus的界面注册，这一步很重要
        EventBus.getDefault().register(this);

        aliyun_back = findViewById(R.id.aliyun_back);
        aliyun_question = findViewById(R.id.aliyun_question);
        aliyun_save = findViewById(R.id.aliyun_save);

        aliyun_appkey = findViewById(R.id.aliyun_appkey);
        aliyun_AccessKeyID = findViewById(R.id.aliyun_AccessKeyID);
        aliyun_AccessKeySecret = findViewById(R.id.aliyun_AccessKeySecret);
        aliyun_volume = findViewById(R.id.aliyun_volume);
        aliyun_speed = findViewById(R.id.aliyun_speed);
        aliyun_voice_select = findViewById(R.id.aliyun_voice_select);

        aliyun_tablayout = findViewById(R.id.aliyun_tablayout);
        aliyun_viewpager2 = findViewById(R.id.aliyun_viewpager2);

        userDb = new UserDatabase(getApplicationContext());
        UserModel userModel = userDb.select();
        aliyun_appkey.setText(userModel.getAliyunAppkey());
        aliyun_AccessKeyID.setText(userModel.getAliyunAccessKeyID());
        aliyun_AccessKeySecret.setText(userModel.getAliyunAccessKeySecret());
        aliyun_volume.setText(userModel.getAliyunVolume().isEmpty()?"50":userModel.getAliyunVolume());
        aliyun_speed.setText(userModel.getAliyunSpeedLevel().isEmpty()?"0":userModel.getAliyunSpeedLevel());
        aliyun_voice_select.setText(userModel.getAliyunVoiceSelect());
        font_name = userModel.getAliyunFontName();
        init();
    }
    public void init(){

        aliyun_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        aliyun_question.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_question();
            }
        });
        aliyun_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(aliyun_appkey.getText().toString().isEmpty() || aliyun_AccessKeyID.getText().toString().isEmpty() || aliyun_AccessKeySecret.getText().toString().isEmpty()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请先配置密钥！");
                    return ;
                }

                Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
                Matcher matcherAppkey = pattern.matcher(aliyun_appkey.getText().toString());
                Matcher matcherAccessKeyID = pattern.matcher(aliyun_AccessKeyID.getText().toString());
                Matcher matcherAccessKeySecret = pattern.matcher(aliyun_AccessKeySecret.getText().toString());

                if (matcherAppkey.find()) {
                    ToastBottomUtils.Setinfo(getApplicationContext(),"APPKey检测出其他字符（除字母数字外）");
                    return ;
                }
                if (matcherAccessKeyID.find()) {
                    ToastBottomUtils.Setinfo(getApplicationContext(),"AccessKeyID检测出其他字符（除字母数字外）");
                    return ;
                }
                if (matcherAccessKeySecret.find()) {
                    ToastBottomUtils.Setinfo(getApplicationContext(),"AccessKeySecret检测出其他字符（除字母数字外）");
                    return ;
                }
                //音量，Integer 范围是0~100，可选，默认50。
                if(Float.valueOf(aliyun_volume.getText().toString()) < 0 ||  Float.valueOf(aliyun_volume.getText().toString()) > 100 ){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"音量设置范围不规范！");
                    return ;
                }
                //语速，Integer 取值范围：-500~500，默认值：0
                if(Float.valueOf(aliyun_speed.getText().toString()) < -500 ||  Float.valueOf(aliyun_speed.getText().toString()) > 500 ){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"语速设置范围不规范！");
                    return ;
                }
                UserModel userModel =  new UserModel();
                userModel.setAliyunAppkey(aliyun_appkey.getText().toString());
                userModel.setAliyunAccessKeySecret(aliyun_AccessKeySecret.getText().toString());
                userModel.setAliyunAccessKeyID(aliyun_AccessKeyID.getText().toString());
                userModel.setAliyunSpeedLevel(aliyun_speed.getText().toString());
                userModel.setAliyunVolume(aliyun_volume.getText().toString());
                userModel.setAliyunVoiceSelect(aliyun_voice_select.getText().toString());
                userModel.setAliyunFontName(font_name);
                userDb.updateAliKey(userModel);

                ToastUtils.Setinfo(getApplicationContext(),"保存成功",1);
            }
        });
        List<Fragment> fragments = new ArrayList<>();
        PageFragment Tongyong = PageFragment.newInstance(0);//通用
        PageFragment Zhibo = PageFragment.newInstance(1);//直播
        PageFragment Kefu = PageFragment.newInstance(2);//客服
        PageFragment Duoyuzhong = PageFragment.newInstance(3);//多语种
        PageFragment Fangyan = PageFragment.newInstance(4);//方言
        PageFragment Yingwen = PageFragment.newInstance(5);//英文
        PageFragment Children = PageFragment.newInstance(6);//儿童
        fragments.add(Tongyong);
        fragments.add(Zhibo);
        fragments.add(Kefu);
        fragments.add(Duoyuzhong);
        fragments.add(Fangyan);
        fragments.add(Yingwen);
        fragments.add(Children);
        Tongyong.setOnVoiceListItemSelect(new PageFragment.OnVoiceListItemSelect() {
            @Override
            public void onClick(int position, String voice_name) {
                font_name = voice_name;
                AliyunVoiceModel model = GetUtil.getSceneVoiceTongyong().get(position);
                aliyun_voice_select.setText(model.getModelScene()+"-"+model.getModelName()+"（"+model.getModelType()+"）");
            }
        });
        Zhibo.setOnVoiceListItemSelect(new PageFragment.OnVoiceListItemSelect() {
            @Override
            public void onClick(int position, String voice_name) {
                font_name = voice_name;
                AliyunVoiceModel model = GetUtil.getSceneVoiceZhibo().get(position);
                aliyun_voice_select.setText(model.getModelScene()+"-"+model.getModelName()+"（"+model.getModelType()+"）");
            }
        });
        Kefu.setOnVoiceListItemSelect(new PageFragment.OnVoiceListItemSelect() {
            @Override
            public void onClick(int position, String voice_name) {
                font_name = voice_name;
                AliyunVoiceModel model = GetUtil.getSceneVoiceKefu().get(position);
                aliyun_voice_select.setText(model.getModelScene()+"-"+model.getModelName()+"（"+model.getModelType()+"）");
            }
        });
        Duoyuzhong.setOnVoiceListItemSelect(new PageFragment.OnVoiceListItemSelect() {
            @Override
            public void onClick(int position, String voice_name) {
                font_name = voice_name;
                AliyunVoiceModel model = GetUtil.getSceneVoiceDuoyuzhong().get(position);
                aliyun_voice_select.setText(model.getModelScene()+"-"+model.getModelName()+"（"+model.getModelType()+"）");
            }
        });
        Fangyan.setOnVoiceListItemSelect(new PageFragment.OnVoiceListItemSelect() {
            @Override
            public void onClick(int position, String voice_name) {
                font_name = voice_name;
                AliyunVoiceModel model = GetUtil.getSceneVoiceFangyan().get(position);
                aliyun_voice_select.setText(model.getModelScene()+"-"+model.getModelName()+"（"+model.getModelType()+"）");
            }
        });
        Yingwen.setOnVoiceListItemSelect(new PageFragment.OnVoiceListItemSelect() {
            @Override
            public void onClick(int position, String voice_name) {
                font_name = voice_name;
                AliyunVoiceModel model = GetUtil.getSceneVoiceYingwen().get(position);
                aliyun_voice_select.setText(model.getModelScene()+"-"+model.getModelName()+"（"+model.getModelType()+"）");
            }
        });
        Children.setOnVoiceListItemSelect(new PageFragment.OnVoiceListItemSelect() {
            @Override
            public void onClick(int position, String voice_name) {
                font_name = voice_name;
                AliyunVoiceModel model = GetUtil.getSceneVoiceChildren().get(position);
                aliyun_voice_select.setText(model.getModelScene()+"-"+model.getModelName()+"（"+model.getModelType()+"）");
            }
        });

        aliyun_appkey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void afterTextChanged(Editable editable) {
                if(fragments != null){
                    String appkey = editable.toString();//editable.toString(),aliyun_appkey.getText().toString()
                    String AccessKeyID = aliyun_AccessKeyID.getText().toString();
                    String AccessKeySecret = aliyun_AccessKeySecret.getText().toString();
                    String speed_level = aliyun_speed.getText().toString();
                    String volume = aliyun_volume.getText().toString();

                    switch (aliyun_viewpager2.getCurrentItem()){
                        case 0:Tongyong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 1:Zhibo.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 2:Kefu.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 3:Duoyuzhong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 4:Fangyan.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 5:Yingwen.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 6:Children.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                    }
                }
            }
        });
        aliyun_AccessKeyID.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void afterTextChanged(Editable editable) {
                if(fragments != null){
                    String appkey = aliyun_appkey.getText().toString();
                    String AccessKeyID = editable.toString();
                    String AccessKeySecret = aliyun_AccessKeySecret.getText().toString();
                    String speed_level = aliyun_speed.getText().toString();
                    String volume = aliyun_volume.getText().toString();

                    switch (aliyun_viewpager2.getCurrentItem()){
                        case 0:Tongyong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 1:Zhibo.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 2:Kefu.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 3:Duoyuzhong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 4:Fangyan.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 5:Yingwen.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 6:Children.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                    }
                }
            }
        });
        aliyun_AccessKeySecret.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void afterTextChanged(Editable editable) {
                if(fragments != null){
                    String appkey = aliyun_appkey.getText().toString();
                    String AccessKeyID = aliyun_AccessKeyID.getText().toString();
                    String AccessKeySecret = editable.toString();
                    String speed_level = aliyun_speed.getText().toString();
                    String volume = aliyun_volume.getText().toString();

                    switch (aliyun_viewpager2.getCurrentItem()){
                        case 0:Tongyong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 1:Zhibo.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 2:Kefu.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 3:Duoyuzhong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 4:Fangyan.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 5:Yingwen.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 6:Children.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                    }
                }
            }
        });
        aliyun_volume.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void afterTextChanged(Editable editable) {
                if(fragments != null){
                    String appkey = aliyun_appkey.getText().toString();
                    String AccessKeyID = aliyun_AccessKeyID.getText().toString();
                    String AccessKeySecret = aliyun_AccessKeySecret.getText().toString();
                    String speed_level = aliyun_speed.getText().toString();
                    String volume = editable.toString();

                    switch (aliyun_viewpager2.getCurrentItem()){
                        case 0:Tongyong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 1:Zhibo.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 2:Kefu.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 3:Duoyuzhong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 4:Fangyan.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 5:Yingwen.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 6:Children.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                    }
                }
            }
        });
        aliyun_speed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override
            public void afterTextChanged(Editable editable) {
                if(fragments != null){
                    String appkey = aliyun_appkey.getText().toString();
                    String AccessKeyID = aliyun_AccessKeyID.getText().toString();
                    String AccessKeySecret = aliyun_AccessKeySecret.getText().toString();
                    String speed_level = editable.toString();
                    String volume = aliyun_volume.getText().toString();

                    switch (aliyun_viewpager2.getCurrentItem()){
                        case 0:Tongyong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 1:Zhibo.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 2:Kefu.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 3:Duoyuzhong.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 4:Fangyan.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 5:Yingwen.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                        case 6:Children.setAliyunConfig(appkey,AccessKeyID,AccessKeySecret,speed_level,volume);break;
                    }
                }
            }
        });
        aliyun_viewpager2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
//                return PageFragment.newInstance(position,nuiTtsInstance);
                return fragments.get(position);
            }

            @Override
            public int getItemCount() {
                return tar.length;
            }
        });
        //设置tab
        new TabLayoutMediator(aliyun_tablayout, aliyun_viewpager2, (tab, position) -> {
            tab.setText(tar[position]);
        }).attach();
        //设置缓存数量，设置为0即可 这样我们每次滑动一个新的tab时 会创建新的fragment并销毁上一个fragment
        ((RecyclerView)aliyun_viewpager2.getChildAt(0)).setItemViewCacheSize(0);
    }
    //点击疑问
    public void dialog_question(){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(true);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_aliyun_question);
        final TextView dialog_aliyun_msg = window.findViewById(R.id.dialog_aliyun_msg);
        dialog_aliyun_msg.setText(R.string.aliyun_config);
    }

    //任意写一个方法，给这个方法一个@Subscribe注解，参数类型可以自定义，但是一定要与你发出的类型相同
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(TtsMessageEvent ttsMessageEvent){
        switch (ttsMessageEvent.getNumber()) {
            case 1://正确
                ToastUtils.Setinfo(this,ttsMessageEvent.getMessage(),1);
                break;
            case 2://异常
                ToastUtils.Setinfo(this,ttsMessageEvent.getMessage(),2);
                break;
            case 3://底部toast
                ToastBottomUtils.Setinfo(this,ttsMessageEvent.getMessage());
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
    }
}